//edit by lunjiang end
var P = {};
P.init = function(){
    $(".view_position").bind('click',P.Event.ViewPosition);
    $("body").bind('click', P.Event.Body);
    $(".delok").bind('click', P.Event.Confirm.OK);
    $(".delcancle").bind('click', P.Event.Confirm.Cancle);
    $(".btn.btn-small.btn-primary").bind('click', P.Event.Alert);
};
P.ShowTable = function($obj,data){
    var table_head = '  <tr style="display:table-row;"><td colspan="4"><table class="table" style="width:90%; margin:15px auto; border:1px solid #ddd;"><thead><tr><th>职位id</th><th>职位名称</th><th>在职人数</th><th>计划编制</th><th>操作</th></tr></thead><tbody>';
    var table_foot = ' </tbody></table></td></tr>';
    var strTr = "";
    for (var i in data) {
        strTr = strTr + "<tr>"
        var strTd = "";
        if(parseInt(data[i].fact_num) === 0){
            strTd = strTd + "<td>" + data[i].job_id + "</td><td>" + data[i].position_name + '</td><td><a>' + data[i].fact_num + "</a></td><td>" + data[i].plan_num + "</td>";
        }
        else{
            strTd = strTd + "<td>" + data[i].job_id + "</td><td>" + data[i].position_name + '</td><td><a target="_blank" href="'+data[i].list_url +'">' + data[i].fact_num + "</a></td><td>" + data[i].plan_num + "</td>";

        }
        var strOperation = '<td style="width:93px;"><i class="depart_num" style="display: none">0</i><i class="delete icon-trash" style="visibility: visible;height:14px; margin-left:20px;"></i></td>'
        strTd = strTd + strOperation;
        strTr = strTr + strTd + "</tr>";
    }
    table_head = table_head + strTr;
    table_head = table_head + table_foot;
    $(table_head).insertAfter($obj.parent().parent());
    $("tr td table tbody tr").bind('click', P.Event.InnerTrEvent);
    $("tr td table tbody tr").bind('mouseover', P.Event.OnMouseOverTr);
    $("tr td table tbody tr").bind('mouseout', P.Event.OnMouseOutTr);
    $(".delete.icon-trash").bind('click',function(event){
        $(this).addClass("identity_del");
        var num = parseInt($(this).parent().parent().children("td:eq(2)").children("a").html());//在职人数获取
        if (num > 0) {
            $('#alertDialog').modal();//窗口显示
            return;
        }
        $("#confirmDialog").modal();
        event.stopPropagation();
    });
};
P.Event = {};
P.Event.InnerTrEvent= function(event){
    var $obj = $(this);
    if ($obj.attr("v")) {
        //have clicked again!!!
        event.stopPropagation();
        return;
    }
    if ($("tr[v='1']").attr("v") == 1) {
        //have existed node that edit vale ,so,we shoud submit the value
        $old_node = $("tr[v='1']");

        var result = P.Logic.edit($old_node);
        if(!result){
            event.stopPropagation();
            return;
        }
        $old_node.css("background", "#ffffff");
        P.Dom.replaceTr($old_node);
        $old_node.attr("v", null);
        $obj.attr("v", 1);
        $obj.css("background", "#fdf0e6");
        P.Dom.replaceInput($obj);
        event.stopPropagation();
        return;
    }
    $obj.css("background","#fdf0e6");
    $obj.attr("v",1);
    P.Dom.replaceInput($obj);
    event.stopPropagation();
};
P.Event.Body = function(){
    if ($("tr[v='1']").attr("v") == 1){
        $old_node = $("tr[v='1']");
        var result = P.Logic.edit($old_node);
        if(!result){
            return;
        }
        $old_node.css("background", "#ffffff");
        P.Dom.replaceTr($old_node);
        $old_node.attr("v", null);
    }
};
P.Event.ViewPosition= function(event){
    $obj = $(this);
    var status = $obj.html();
    if (status == "收起") {
        $obj.html("查看");
        $obj = $obj.parent("td").parent("tr").next("tr").replaceWith("");

        //            $obj.parent().removeChild($obj);
        return;
    }
    var departID = $obj.parent("td").parent("tr").children("td:eq(0)").html();
    $.post(viewPositionUrl, {'departID':departID}, function (data) {
        data = eval('(' + data + ')');
        if (data.errcode) {
            P.ShowTable($obj,data.data);
            $obj.html("收起")
        }
    });
    event.stopPropagation();
};
P.Event.DelPosition = function(){
    var $obj =  $(".identity_del").parent().parent();
    var jobID = $.trim($obj.children("td:first").html());
    jQuery.ajax({
        url:delPositionUrl,
        data:{'jobID':jobID},
        type:'post',
        success:function (result) {
            var data = eval('(' + result + ')');
            if (data.errcode) {
                $obj.replaceWith("");
                var lableInfo = $(".btn.btn-small.disabled");
                lableInfo.html(lableInfo.html().replace(/，(\d+)/, function () {
                    return "，"+(parseInt(RegExp.$1) - 1);
                }));
                return;
            }
            $(".identity_del").removeClass("identity_del");

        }
    });
};
P.Event.Confirm = {};
P.Event.Confirm.OK = function(){
    P.Event.DelPosition();
};
P.Event.Confirm.Cancle = function(){
    $(".identity_del").removeClass("identity_del");
};
P.Event.Alert = function(){
    $(".identity_del").removeClass("identity_del");
};
P.Event.OnMouseOverTr = function(){
    var num = parseInt($.trim($(this).children("td:eq(2)").children("a").html()));
    if(num == 0){
    $(this).find(".delete.icon-trash").css("display","inline-block");
    }
}
P.Event.OnMouseOutTr = function(){
    $(this).find(".delete.icon-trash").css("display","none");
}
P.Paras = {};
P.Dom = {};
P.Dom.replaceTr =  function($obj){
    $obj.attr("v", 1);
    var formation = $obj.children("td:eq(3)").find("input").val();
    $obj.children("td:eq(3)").html(formation);
}
P.Dom.replaceInput = function($obj){
    var formation = $obj.children("td:eq(3)").html();
    P.Paras.formation = formation;
    $obj.children("td:eq(3)").html('<input type="text" class="formation" maxlength="4"  style="margin-bottom:0;width: 35px!important;" value="'+formation+'"/>');
    return;
}
P.Dom.replaceError = function(class_name){
    var div_begain = '<div class="control-group error"><td class="controls">';
    var div_end = '<input type="text"  value="" class="formation"></td></div>';
    var html = div_begain + div_end;
    $('.formation').parent().html(html);

}
P.Validate= {};
P.Validate.isEmpty=function(){

    var formation = $.trim($(".formation").val());
    var int_formation = parseInt(formation);
    //为空验证 begain
    if (!formation) {
        if (!$.trim($(".formation").val())) {
            P.Dom.replaceError('formation');
            return true;
        }
    }
    if (int_formation < 0) {
        P.Dom.replaceError('formation');
        return true;
    }
    //验证foramiton 为整数
    //var   type="^[1-9]\d*$|0$";
    var type=(formation.length===1) ? "^[0-9]" : "^[1-9][0-9]*$";
    var   re   =   new   RegExp(type);
    if(formation.match(re)==null)
    {
        P.Dom.replaceError('formation');
        return true;
    }
    if(formation.indexOf('.')>0){
        P.Dom.replaceError('formation');
        return true;
    }

    //为空验证end
    return false;
};
P.Validate.Error=function(class_name){
    var div_begain ='<div class="control-group error"><td class="controls">';
    var div_end ='<input type="text" class="'+ class_name+'" value=""></a></td></div>';
    var html = div_begain  + div_end;
    var var_p = "."+class_name;
    $(var_p).parent().html(html);
};

P.Dialog = {};
P.Dialog.delDialog= function(){
    var num = parseInt($(this).parent().parent().children("td:eq(2)").html());//在职人数获取
    if (num > 0) {
        $('#alertDialog').modal();//窗口显示
        return;
    }
    var id = $.trim($(this).parent().parent().children("td:first").html());
    var $obj = $(this);
    $obj.addClass("identity_del");
    $('#confirmDialog').modal();//窗口显示
    //取消按扭事件绑定
    event.stopPropagation();
    return;
};

P.Logic = {};
P.Logic.edit = function($obj){
    var jobID = $obj.children("td").first().html();
    var formation = $(".formation").val();
    if(formation == P.Paras.formation)
    {
        //alert("is the same");
        return true;
    }
    if(P.Validate.isEmpty())
    {
        return;
    }
    var result;
    jQuery.ajax({
        async:false,
        url:editPostionUrl,
        data:{'jobID':jobID,'formation':formation},
        type:'post',
        success:function (data) {
            var data = eval('(' + data + ')');
            if(data.errcode){
                result = true;
                return;
            }
            result = false;
            return;

        }
    });
    return result;

};









$.ready((function () {
    P.init();

    var skill;
    //点击 添加职位 绑定事件
    $(".iconsu").bind('click', function () {
        $obj = $(this);
        $(".sty_border").remove();
        $("input[jhbz='jhbz']").val('');
        $("select[sel='sel']").html('');
        var depate = $obj.attr("skill"), departName = $obj.attr("depart"), departid = $obj.attr("departid");
        skill= depate;

//        $.post(viewPositionUrl, {'departID':departid, 'skill':depate}, function (data) {
//            data = eval('(' + data + ')');
//            if (data.errcode == 1) {
//                for (var i in data) {
//                    for (var j in data[i]) {
//                        var result = data[i][j];
//
//                        $("select[sel='sel']").append('<option value="' + result.job_id + '">' + result.job_name + '</option>')
//                    }
//                }
//            }
//        });
        $("#function_id_add").val(skill);
        $(".depart").text(departName);
        $('#departID').val(departid);  //添加部门id 和部门name
    });
    var positionResult = false;
    function bindAutocomplete(){
        var trigerObj;
        $(".position").autocomplete({
            source: function(request, response) {
                trigerObj = $(this.element[0]);
                $.ajax({
                    url:searchPositionUrl,
                    dataType: "json",
                    data: {
                        function_id:skill,
                        name: request.term
                    },
                    success: function(data) {
                        response( $.map( data.data, function( item ) {
                            return {
                                label:  item.position_name ,
                                value:  item.position_name,
                                id:item.position_id
                            }
                        }));
                    }
                });
            },
            select: function( event, ui ) {
                var positionId = ui.item.id;
                positionResult = true;
                trigerObj.parent().children(".positionID").val(positionId);
                //trigerObj.next("input[type='hidden']").val();

            }
        });
        $(".position").bind("keydown",function(event){
            if((event.keyCode == 13 && positionResult == true)||(event.keyCode == 9 && positionResult == true) || (event.keyCode == 32 && positionResult == true)){
                return;
            }
            positionResult = false;
        });
        $(".position").bind("blur",function(){
            if(!positionResult){
                $(".leader_id").val("");
                $(".leader_job").val("");
                $(this).parent().find(".positionID").val("");
            }
        });
    }
    bindAutocomplete();


    //点击保存 验证添加职位信息 并且发送AJAX请求
    $("#addDepart").validate({
        submitHandler:function (form) {
            //  向后台提交添加职位数据
            $.post(addPostionUrl,$(form).serialize(),function(data){
                var data = eval('('+data+')');
                var msg=data.msg ? data.msg :'添加成功！';
                $('#err').text(msg).show();
                setTimeout(function () {
                    $('#err').hide().text('')
                }, 3000);
            });
        },
        errorPlacement:function (error, element) {
            if (element.is(":radio"))
                error.appendTo(element.parent().next().next()); else if (element.is(":checkbox"))
                error.appendTo(element.next()); else
                element.parent().append(error);
        },
        errorClass:"invalid"
    });
    var i = 1;
    //点击添加职位克隆
    $('.contiAdd').bind('click', function () {
        var lastElm = $('.jobItem').last();
        lastElm.after('<div class="jobItem sty_border">' + lastElm.html().replace(/\[(\d+)\]/g,function () {
            return '[' + (parseInt(RegExp.$1) + 1) + ']';
        }).replace(/<label class="?:error|invalid" .*<\/label>/g, '') + '</div>');
        lastElm.next().find(".positionID").val("");
        bindAutocomplete();
        i++;
        if(i>19){
            $('.contiAdd').hide();
            return
        }
    });
})());
//添加部门
$('#myModal').on('hidden', function () {
    $(".position ").val("");
    $("#function_id").val("");
})
//删除取消
//删除职位弹出事件
function showDelDialog(event) {
    var num = parseInt($(this).parent().parent().children("td:eq(2)").html());//在职人数获取
    if (num > 0) {
        $('#alertDialog').modal();//窗口显示
        return;
    }

    var id = $.trim($(this).parent().parent().children("td:first").html());
    var $obj = $(this);
    $obj.addClass("identity_del");
    $('#confirmDialog').modal();//窗口显示
    //取消按扭事件绑定
    event.stopPropagation();
    return;
}
//删除职位

function delPosition(){
    var $obj =  $(".identity_del").parent().parent();
    var jobID = $.trim($obj.children("td:first").html());
    jQuery.ajax({
        url:delPositionUrl,
        data:{'jobID':jobID},
        type:'post',
        success:function (result) {
            var data = eval('(' + result + ')');
            if (data.errcode) {
                $obj.replaceWith("");
                var lableInfo = $(".div_title");
                lableInfo.html(lableInfo.html().replace(/(\d+)/, function () {
                    return parseInt(RegExp.$1) - 1;
                }));

                return;
            }
            $(".identity_del").removeClass("identity_del");
        }
    });
}
